<?php
/**
 * Created by PhpStorm.
 * User: z-benjamin
 * Date: 16/9/20
 * Time: 下午1:47.
 */

namespace wxml\models\order;

use common\libs\Util;
use wxml\models\order\AR\OrderAR;
use wxml\models\user\AR\UserAR;
use wxml\models\Weixin;
use yii;
use common\libs\CommonModel;
use wxml\models\product\AR\ProductAR;
use common\libs\Pagination;
use yii\helpers\ArrayHelper;

class Order extends CommonModel
{
    public function createOrder($product_id, $address, $user)
    {
        $product = ProductAR::findOne(['id' => $product_id]);
        if (!$product) {
            $this->setError(-1, '产品不存在');

            return false;
        }
        $output = [];
        $dbTrans = Yii::$app->db->beginTransaction();
        try {

            //创建订单主信息
            $order_main = new OrderAR();
            $order_main->user_id = $user->id;
            $order_main->product_id = $product->id;
            $order_main->product_price = $product->sale_price;
            $order_main->trade_price = 0;
            $order_main->total_price = $product->sale_price;
            $order_main->amount = 1;
            $order_main->status = 'CREATED';
            $order_main->order_no = 'BOOK_'.time().Util::getRandCode(6, 1);
            $order_main->create_time = time();

            $order_main->address = $address['detailInfo'];
            $order_main->telphone = $address['telNumber'];
            $order_main->province = $address['provinceName'];
            $order_main->city = $address['cityName'];
            $order_main->country = $address['countyName'];
            $order_main->receiver = $address['userName'];

            $order_save_result = $order_main->save();
            if (!$order_save_result) {
                throw new \Exception('保存订单信息错误');
            }
            $new_order_id = Yii::$app->db->getLastInsertId();

            $output = ['order_id' => $new_order_id];
            $dbTrans->commit();
        } catch (\Exception $e) {
            $dbTrans->rollback();
            $this->errMsg = $e->getMessage();

            return false;
        }

        return $output;
    }

    public function detail($order_id, $user)
    {
        $order = [];
        $order_main = OrderAR::findOne(['id' => $order_id]);
        if (!$order_main) {
            $this->setError(-1, '订单不存在');

            return false;
        }
        if ($order_main->user_id != $user->id) {
            $this->setError(-1, '这笔订单不属于您');

            return false;
        }

        $product = ProductAR::findOne(['id' => $order_main->product_id]);

        $order['order'] = $order_main->toArray();
        $order['book'] = $product->toArray();

        return $order;
    }

    public function getList($user, $offset = 0, $limit = 10)
    {
        $query = OrderAR::find();
        $query->andWhere(['user_id' => $user->id]);

        $count = $query->count();
        // create a pagination object with the total count
        $pagination = new Pagination(['totalCount' => $count, 'perPage' => $limit, 'limit' => $limit,
                                      'offset' => $offset, ]);
        // limit the query using the pagination and retrieve the articles
        $orders = $query->offset($pagination->offset)->limit($pagination->limit)->with('product')->all();
        $ordersArray = ArrayHelper::toArray($orders);

        foreach ($orders as $key => $order) {
            $product = $order->getProduct()->primaryModel->product;
            $ordersArray[$key]['product'] = $product;
        }

        return array('list' => $ordersArray, 'pages' => $pagination);
    }

    public function orderStatus($order_id)
    {
        $order_main = OrderAR::findOne(['order_id' => $order_id]);

        return ['status' => $order_main ? $order_main['status'] : 0];
    }

    public function orderPay($order_id, $user)
    {
        $order = OrderAR::findOne(['id' => $order_id]);
        if (!$order) {
            $this->errMsg = '订单信息异常';

            return false;
        }
        if ($order->user_id != $user->id) {
            $this->setError(-1, '这笔订单不属于您');

            return false;
        }
        if ($order->status != 'CREATED') {
            $this->setError(-1, '订单状态异常');

            return false;
        }
        $product = ProductAR::findOne(['id' => $order->product_id]);
        $weixin = new Weixin();
        $result = $weixin->unifiedorder($product->title, $order->order_no, (int) (100 * $order->total_price), $user->weixin_openid, $order->third_pay_no);
        if ($result === false) {
            $this->setError(-1, $weixin->getErrMsg());

            return false;
        } else {
            return $result;
        }
    }

    public function paySuccess($out_trade_no, $total_fee)
    {
        $order = OrderAR::findOne(['order_no' => $out_trade_no]);
        $user = UserAR::findOne(['id' => $order->user_id]);
        if (!$order) {
            $this->errMsg = '订单不存在';

            return false;
        }
        if ($order->status != 'CREATED') {
            $this->errMsg = '订单状态异常'.$order->status;

            return false;
        }

        $dbTrans = Yii::$app->db->beginTransaction();
        try {
            $order->status = 'PAIED';
            $order->pay_time = time();
            $order->pay_price = $total_fee;
            $order_save_result = $order->save();
            if (!$order_save_result) {
                Yii::error('订单支付失败:'.print_r($order, true));
                throw new \Exception('更新订单状态失败');
            }
            $dbTrans->commit();
        } catch (\Exception $e) {
            $dbTrans->rollback();
            $this->errMsg = $e->getMessage();

            return false;
        }

        $weixinTemplateParams = ['keyword1' => $user->nickname, 'keyword2' => $order->out_order_id,
                                 'keyword3' => $order->total_price, 'keyword4' => $order->product_title,
                                 'url' => 'http://weixin.lvacation.cn/weixin/entrance?state=%2Fweixin%2Fshare_entrance%3Fpath%3D%2Forder%2Fdetail%3Forder_id%3D'.$order->order_id, ];
        $weixin = new Weixin();
        $weixin->sendTemplateMessage('OrderPaySuccess', 'ojwZ9v9UVTinUDXUmv4g-93GG2Hg', $weixinTemplateParams);
        $weixin->sendTemplateMessage('OrderPaySuccess', 'ojwZ9v4Eg_WO3ijoK9aFnFPV6M9E', $weixinTemplateParams);
        $weixin->sendTemplateMessage('OrderPaySuccess', $user->weixin_openid, $weixinTemplateParams);

        return true;
    }
}
